package com.liit.controller.system;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.liit.annotation.SystemLog;
import com.liit.controller.index.BaseController;
import com.liit.entity.RoleFormMap;
import com.liit.entity.UserFormMap;
import com.liit.entity.UserRoleFormMap;
import com.liit.exception.SystemException;
import com.liit.mapper.RoleMapper;
import com.liit.mapper.UserMapper;
import com.liit.plugin.PageView;
import com.liit.util.Common;
import com.liit.util.JsonUtils;
import com.liit.util.POIUtils;
import com.liit.util.PasswordHelper;
import com.liit.util.PropertiesUtils;

/**
 * 
 * @author liit 2014-11-19
 * @Email: mmm333zzz520@163.com
 * @version 3.0v
 */
@Controller
@RequestMapping("/user/")
public class UserController extends BaseController {
	@Inject
	private UserMapper userMapper;
	@Inject
	private RoleMapper roleMapper;

	@RequestMapping("list")
	public String listUI(Model model) throws Exception {
		model.addAttribute("res", findByRes());
		model.addAttribute("role", roleMapper.findByWhere(new RoleFormMap()));
		return Common.BACKGROUND_PATH + "/system/user/list";
	}

	@ResponseBody
	@RequestMapping("findByPage")
	public PageView findByPage(String pageNow, String pageSize, String column, String sort) throws Exception {
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		userFormMap.put("deletestatus", Common.COMMON_STATUS_ENABLE);// 未删除用户
		userFormMap = toFormMap(userFormMap, pageNow, pageSize, userFormMap.getStr("orderby"));
		userFormMap.put("column", column);
		userFormMap.put("sort", sort);
		pageView.setRecords(userMapper.findUserPage(userFormMap));// 不调用默认分页,调用自已的mapper中findUserPage
		return pageView;
	}

	@RequestMapping("/export")
	public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String fileName = "用户列表";
		UserFormMap userFormMap = findHasHMap(UserFormMap.class);
		// exportData =
		// [{"colkey":"sql_info","name":"SQL语句","hide":false},
		// {"colkey":"total_time","name":"总响应时长","hide":false},
		// {"colkey":"avg_time","name":"平均响应时长","hide":false},
		// {"colkey":"record_time","name":"记录时间","hide":false},
		// {"colkey":"call_count","name":"请求次数","hide":false}
		// ]
		String exportData = userFormMap.getStr("exportData");// 列表头的json字符串

		List<Map<String, Object>> listMap = JsonUtils.parseJSONList(exportData);
		listMap.remove(listMap.get(0));
		List<UserFormMap> lis = userMapper.findUserPage(userFormMap);
		if(lis.size()>0){
			for(int i=0;i<lis.size();i++){
				if("0".equals(lis.get(i).get("locked").toString())){
					lis.get(i).put("locked","启用");
				}else{
					lis.get(i).put("locked","禁用");		
				}
			}
		}
		POIUtils.exportToExcel(response, listMap, lis, fileName);
	}

	@RequestMapping("addUI")
	public String addUI(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/user/add";
	}

	@ResponseBody
	@RequestMapping("addEntity")
	@SystemLog(module = "系统管理", methods = "用户管理-新增用户")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false)
	// 需要事务操作必须加入此注解
	public String addEntity(String txtGroupsSelect) {
		try {
			UserFormMap userFormMap = getFormMap(UserFormMap.class);
			userFormMap.put("txtGroupsSelect", txtGroupsSelect);
			PasswordHelper passwordHelper = new PasswordHelper();
			userFormMap.set("password", "123456789");
			passwordHelper.encryptPassword(userFormMap);
			userMapper.addEntity(userFormMap);// 新增后返回新增信息
			if (!Common.isEmpty(txtGroupsSelect)) {
				String[] txt = txtGroupsSelect.split(",");
				UserRoleFormMap userGroupsFormMap = new UserRoleFormMap();
				for (String roleId : txt) {
					userGroupsFormMap.put("userId", userFormMap.get("id"));
					userGroupsFormMap.put("roleId", roleId);
					userMapper.addEntity(userGroupsFormMap);
				}
			}
		} catch (Exception e) {
			throw new SystemException("添加账号异常");
		}
		return "success";
	}

	@ResponseBody
	@RequestMapping("deleteEntity")
	@Transactional(readOnly = false)
	// 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-删除用户")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteEntity() throws Exception {
		String[] ids = getParaValues("ids");
		for (String id : ids) {
			userMapper.deleteByAttribute("userId", id, UserRoleFormMap.class);
			userMapper.deleteByAttribute("id", id, UserFormMap.class);
		}
		return "success";
	}

	@RequestMapping("editUI")
	public String editUI(Model model) throws Exception {
		String id = getPara("id");
		if (Common.isNotEmpty(id)) {
			model.addAttribute("user", userMapper.findbyFrist("id", id, UserFormMap.class));
		}
		return Common.BACKGROUND_PATH + "/system/user/edit";
	}

	@ResponseBody
	@RequestMapping("editEntity")
	@Transactional(readOnly = false)
	// 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-修改用户")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String editEntity(String txtGroupsSelect) throws Exception {
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		userFormMap.put("txtGroupsSelect", txtGroupsSelect);
		userFormMap.put("area", getPara("userFormMap.area"));
		userFormMap.put("street", getPara("userFormMap.street"));
		userMapper.editEntity(userFormMap);
		userMapper.deleteByAttribute("userId", userFormMap.get("id") + "", UserRoleFormMap.class);
		if (!Common.isEmpty(txtGroupsSelect)) {
			String[] txt = txtGroupsSelect.split(",");
			for (String roleId : txt) {
				UserRoleFormMap userGroupsFormMap = new UserRoleFormMap();
				userGroupsFormMap.put("userId", userFormMap.get("id"));
				userGroupsFormMap.put("roleId", roleId);
				userMapper.addEntity(userGroupsFormMap);
			}
		}
		return "success";
	}

	/**
	 * 验证账号是否存在
	 * 
	 * @author liit Email：mmm333zzz520@163.com date：2014-2-19
	 * @param name
	 * @return
	 */
	@RequestMapping("isExist")
	@ResponseBody
	public boolean isExist(String name) {
		UserFormMap account = userMapper.findbyFrist("accountName", name, UserFormMap.class);
		if (account == null) {
			return true;
		} else {
			return false;
		}
	}

	// 密码修改
	@RequestMapping("updatePassword")
	public String updatePassword(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/user/updatePassword";
	}

	// 保存新密码
	@RequestMapping("editPassword")
	@ResponseBody
	@Transactional(readOnly = false)
	// 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-修改密码")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String editPassword() throws Exception {
		// 当验证都通过后，把用户信息放在session里
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		// 这里对修改的密码进行加密
		PasswordHelper passwordHelper = new PasswordHelper();
		UserFormMap user = (UserFormMap) SecurityUtils.getSubject().getSession().getAttribute("userSession");
		if (!passwordHelper.validatePassword(user, userFormMap.getStr("password"))) {
			return "原密码错误";
		}
		userFormMap.get("password");
		userFormMap.put("password", userFormMap.get("newpassword"));
		passwordHelper.encryptPassword(userFormMap);
		userMapper.editEntity(userFormMap);
		return "success";
	}

	// 个人信息修改
	@RequestMapping("changePersonal")
	public String changePersonal(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/user/updatePersonal";
	}

	// 保存个人信息
	@RequestMapping("editPersonal")
	@ResponseBody
	@Transactional(readOnly = false)
	// 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-修改用户信息")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String editPersonal(@RequestParam(value = "urlName", required = false) MultipartFile urlName, @RequestParam(value = "id", required = false) String id,
			@RequestParam(value = "userName", required = false) String userName) throws Exception {
		UserFormMap userInfo = userMapper.findbyFrist("id", id, UserFormMap.class);
		UserFormMap userFromMap = new UserFormMap();
		userFromMap.put("id", id);
		userFromMap.put("userName", userName);
		String path = PropertiesUtils.findPropertiesKey("file.upload.path") + "headImage/";
		if (urlName.getOriginalFilename() != null && !"".equals(urlName.getOriginalFilename())) {
			String fName = urlName.getOriginalFilename();
			String prefix = fName.substring(fName.lastIndexOf(".") + 1);
			prefix=prefix.toLowerCase();
			String newFileName = String.valueOf(System.currentTimeMillis()) + "." + prefix;
			userFromMap.put("images", newFileName);
			try {
				deleteFile(path + userInfo.getStr("images"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			SaveFileFromInputStream(urlName.getInputStream(), path, newFileName);
			userInfo.put("images", newFileName);
		}
		
		Session session = SecurityUtils.getSubject().getSession();
		userInfo.put("userName", userName);
		session.setAttribute("userSession", userInfo);
		
		userMapper.editEntity(userFromMap);
		return "success";
	}

	public void SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
		FileOutputStream fs = new FileOutputStream(path + filename);
		byte[] buffer = new byte[1024 * 1024];
		int bytesum = 0;
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
	}

	public void deleteFile(String name) throws IOException {
		File fis = new File(name);
		fis.delete();
	}
	@RequestMapping("resetPassword")
	@ResponseBody
	@Transactional(readOnly = false)
	// 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-重置密码")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String resetPassword() throws Exception {
		// 当验证都通过后，把用户信息放在session里
		String[] ids = getPara("ids").split(",");
		for (String id : ids) {
			UserFormMap user=userMapper.findbyFrist("id",id,UserFormMap.class);
			user.put("password","123456789");
			PasswordHelper passwordHelper = new PasswordHelper();
			passwordHelper.encryptPassword(user);
			userMapper.editEntity(user);
		}
		return "success";
	}
}